package com.chukun.concurrency;

import com.chukun.concurrency.annotations.UnThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 代码模拟并发请求
 * 线程不安全的类
 */
@Slf4j
@UnThreadSafe
public class SimulationConcurrencyTest {

    //并发线程总数
    private static final int totalThreadCount=1000;

    //允许同时访问的总数
    private static final int allowThreadCount = 200;

    private static int count=0;

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalThreadCount);
        Semaphore semaphore = new Semaphore(allowThreadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalThreadCount;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                }catch (Exception e){
                    log.error("error count add ",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }

    private static void add(){
        count++;
    }
}
